<template>
  <div class="defineArea">
    <el-divider content-position="center" class="title-center">划定区域</el-divider>
    <div class="initArea">
      <el-select v-model="AreaType" style="margin-right: 10px " placeholder="请选择检测类型">
        <el-option value="hat" label="安全帽检测" />
        <el-option value="phone" label="手机检测" />
        <el-option value="reflect" label="反光服检测" />
        <el-option value="fire" label="烟火检测" />
        <el-option value="smoking" label="吸烟检测" />
        <el-option value="sundry" label="杂物检测" />
        <el-option value="sleep" label="睡觉检测" />
        <el-option value="fence" label="电子围栏" />
        <el-option value="speed" label="速度检测" />
      </el-select>
      <el-button type="primary" round @click="dataInit">获取数据</el-button>
      <el-button type="warning" round @click="resetCanvas">重置</el-button>
      <el-button type="info" round @click="btnUpload">上传数据</el-button>
    </div>
    <div style="margin-top: 10px" class="canvasInit">
      <canvas
        v-if="canvas"
        id="canvas"
        :width="imgWidth"
        :height="imgHeight"
        @mousedown="canvasDown($event)"
        @mousemove="canvasMove($event)"
        @mouseup="canvasUp($event)"
      />
      <el-empty v-else />
    </div>
  </div>
</template>

<script>
import { getDetectImg, postPointList } from '@/api/fence'
import { BASE_DETECT_URL } from '@/api/realTime'

import debounce from 'lodash.debounce'

export default {
  name: 'DefineArea',
  data() {
    return {
      canvas: false,
      reactError: false,
      moving: false,
      canvasStart: false,
      AreaType: 'hat',
      imgWidth: 500,
      imgHeight: 500,
      imgUrl: '',
      lineArray: [],
      rect: {
        rightTopX: 0,
        rightTopY: 0,
        rightBottomX: 0,
        rightBottomY: 0,
        leftBottomX: 0,
        leftBottomY: 0
      },
      rectPos: {
        left: 0,
        top: 0,
        width: 0,
        height: 0
      },
      moveX: 0,
      moveY: 0,
      toX: 0,
      toY: 0,
      pointArray: []
    }
  },
  watch: {
    AreaType: {
      handler() {
        this.resetCanvas()
        this.lineArray = []
        this.dataInit()
      },
      immediate: false,
      deep: true
    }
  },
  mounted() {
    this.dataInit()
  },
  methods: {
    async btnUpload() {
      const data = {
        type: this.AreaType,
        pointArray: this.pointArray
      }
      const dataJson = JSON.stringify(data)
      console.log(dataJson)
      await postPointList(dataJson).then(res => {
        if (res.status === 1) {
          this.$message({
            message: '上传成功',
            type: 'success'
          })
        } else {
          this.$message({
            message: '上传失败',
            type: 'error'
          })
        }
      })
    },
    drawRect(e) {
      if (this.moving) {
        this.context.lineWidth = 1
        this.context.shadowBlur = 1
        this.context.shadowColor = '#ce6e31'
        this.context.strokeStyle = '#ce6e31'
        this.toX = e.offsetX
        this.toY = e.offsetY
        if (this.toX - this.moveX >= 0 && this.toY - this.moveY >= 0) {
          this.context.beginPath()
          this.context.rect(this.moveX, this.moveY, this.toX - this.moveX, this.toY - this.moveY)
          this.context.closePath()
          this.context.stroke()
        } else {
          this.drawRectError()
          this.rectError = true
        }
      }
    },
    reDrawRect(moveX, moveY, toX, toY) {
      this.context.beginPath()
      this.context.rect(moveX, moveY, toX - moveX, toY - moveY)
      this.context.closePath()
      this.context.stroke()
    },
    getImgSize(url) {
      return new Promise((resolve, reject) => {
        const imgObj = new Image()
        imgObj.src = url
        imgObj.onload = () => {
          resolve({
            width: imgObj.width,
            height: imgObj.height
          })
        }
      })
    },
    initCanvas() { // 初始化
      this.canvasStart = true
      // 初始化canvas
      const canvas = document.querySelector('#canvas')
      this.context = canvas.getContext('2d')
      // console.log(canvas.getBoundingClientRect())
      const rect = canvas.getBoundingClientRect()
      this.rectPos.left = rect.left
      this.rectPos.top = rect.top
      this.rectPos.width = rect.width
      this.rectPos.height = rect.height
      // 84test
      this.context.lineWidth = 1
      this.context.shadowBlur = 1
      this.context.shadowColor = '#ce6e31'
      this.context.strokeStyle = '#ce6e31'
      const bgImg = new Image()
      bgImg.src = this.imgUrl
      bgImg.crossOrigin = ''
      bgImg.onload = () => {
        this.context.drawImage(bgImg, 0, 0)
      }
      // this.context.drawImage(bgImg, 0, 0)
    },
    async dataInit() {
      this.canvas = true
      let type = ''
      if (!this.$store.getters.useVideo) {
        switch (this.AreaType) {
          case 'hat':
            type = 'hat'
            break
          case 'phone':
            type = 'phone'
            break
          case 'reflect':
            type = 'reflect'
            break
          case 'fire':
            type = 'fire'
            break
          case 'smoking':
            type = 'smoking'
            break
          case 'sundry':
            type = 'sundry'
            break
          case 'sleep':
            type = 'sleep'
            break
          case 'speed':
            type = 'speed'
            break
          case 'fence':
            type = 'fence'
            break
          default:
            type = 'hat'
        }
        const { URL } = await getDetectImg(type)
        this.imgUrl = BASE_DETECT_URL + URL
        // 本地测试
        // this.imgUrl = 'http://localhost:9528/OIP.jpg'
      } else {
        // TODO: 从摄像头提取数据
      }
      const imgSize = this.getImgSize(this.imgUrl)
      imgSize.then((result) => {
        console.log(result)
        this.imgWidth = result.width
        this.imgHeight = result.height
      })
      this.initCanvas()
    },
    canvasDown(e) {
      this.rectError = false
      this.moving = true
      this.moveX = e.offsetX
      this.moveY = e.offsetY
    },
    canvasMove(e) {
      if (this.moving === true && this.canvasStart === true) {
        const bgImg = new Image()
        bgImg.src = this.imgUrl
        bgImg.crossOrigin = ''
        this.context.drawImage(bgImg, 0, 0)
        for (let i = 0; i < this.lineArray.length; i++) {
          this.reDrawRect(this.lineArray[i][0], this.lineArray[i][1], this.lineArray[i][2], this.lineArray[i][3])
        }
        this.drawRect(e)
      }
    },
    canvasUp(e) {
      // TODO:数据处理
      this.lineArray.push([this.moveX, this.moveY, this.toX, this.toY])
      const points = {
        leftTopX: this.moveX,
        leftTopY: this.moveY,
        leftBottomX: this.moveX,
        leftBottomY: this.toY,
        rightTopX: this.toX,
        rightTopY: this.moveY,
        rightBottomX: this.toX,
        rightBottomY: this.toY
      }
      const pointArray = []
      pointArray.push([points.leftTopX, points.leftTopY], [points.leftBottomX, points.leftBottomY], [points.rightTopX, points.rightTopY], [points.rightBottomX, points.rightBottomY])
      console.log('lineArray:' + this.lineArray)
      console.log(pointArray)
      this.pointArray = pointArray
      // 重置
      this.moving = false
      this.toX = 0
      this.toY = 0
      this.moveY = 0
      this.moveX = 0
      this.rect.leftBottomX = 0
      this.rect.leftBottomY = 0
      this.rect.rightTopX = 0
      this.rect.rightTopY = 0
      this.rect.rightBottomX = 0
      this.rect.rightBottomY = 0
    },
    resetCanvas() {
      this.context.fillStyle = '#fff'
      this.context.clearRect(0, 0, this.imgWidth, this.imgHeight)
      this.context.fillRect(0, 0, this.imgWidth, this.imgHeight)
      this.context.fillStyle = '#000'
      this.lineArray = []
      // this.pointArray = []
      // this.lineIndex = []
      // this.colorArray = []
      // this.lineList = []
      this.canvasStart = false
      this.canvas = false
      this.rectError = false
      this.initCanvas()
    },
    drawRectError: debounce(function() {
      this.$message.error('请选择正确的矩形区域')
    }, 100)
  }
}
</script>

<style scoped>
/deep/.el-divider__text{
  font-size: 20px;
}
.initArea, .canvasInit{
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
